import json
import re
from collections import Counter
from datetime import datetime

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt

from model.predict import preModel
from utils.error import *
from utils.getChartData import *

# from model.获取csv import generate_city_csv
# from model.pre2 import predict_weather
from model.获取csv2 import generate_city_csv
from model.pre5 import predict_weather
# Create your views here.
from django.views.decorators.http import require_POST
from openai import OpenAI


# 登录
@csrf_exempt
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html', {})
    else:
        email = request.POST.get('email')
        password = request.POST.get('password')
        print(email, password)
        try:
            user = User.objects.get(email=email, password=password)
            request.session['email'] = user.email
            return redirect('index')
        except:
            return errorResponse(request, '请输入正确的账号和密码')


# 注册
@csrf_exempt
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html', {})
    else:
        email = request.POST.get('email')
        password = request.POST.get('password')
        checkPassword=request.POST.get('checkPassword')
        print(email, password, checkPassword)
        try:
            User.objects.get(email=email)
            return errorResponse(request, '账号已存在')
        except:
            if not email or not password or not checkPassword:
                return errorResponse(request,'信息不允许为空')
            if password != checkPassword:
                return errorResponse(request,'两次密码不一致')
            User.objects.create(email=email, password=password)
            return redirect('/userApp/login')
    return render(request, 'register.html')

# 退出登录
def logOut(request):
    return redirect('/userApp/login')

# 用户信息
def userinfo(request):
    uemail = request.session.get('email')
    try:
        userInfo = User.objects.get(email=uemail)
    except User.DoesNotExist:
        return HttpResponse("用户不存在")

    if request.method == 'POST':
        email = request.session.get('email')
        user = User.objects.get(email=email)


        user.username = request.POST.get('username')
        user.email = request.POST.get('email')
        user.phone_number = request.POST.get('phoneNumber')
        user.address = request.POST.get('address')
        user.birthday = request.POST.get('birthday')
        user.save()

        return redirect('userinfo')
    else:
        # Get user info and display
        return render(request, 'userinfo.html', {'userInfo': userInfo})
# 修改密码
def pwdchange(request):
    uemail = request.session.get('email')
    try:
        userInfo = User.objects.get(email=uemail)
    except User.DoesNotExist:
        return HttpResponse("用户不存在")

    if request.method == 'POST':
        email = request.session.get('email')
        user = User.objects.get(email=email)
        # 验证旧密码
        old_password = request.POST.get('oldPassword')
        if old_password != userInfo.password:
            print(old_password)
            print(userInfo.password)
            return HttpResponse("旧密码不正确")

        # 获取新密码和确认密码
        new_password = request.POST.get('newPassword')
        check_password_new = request.POST.get('checkPassword')

        # 密码验证
        if not new_password or not check_password_new:
            return HttpResponse("新密码和确认密码不能为空")
        if new_password != check_password_new:
            return HttpResponse("新密码和确认密码不一致")
        if len(new_password) < 6:
            return HttpResponse("新密码长度至少为6位")

        # 更新密码
        # userInfo.password = make_password(new_password)
        userInfo.password = new_password
        userInfo.save()

        # 返回密码修改成功页面
        return HttpResponse("密码修改成功")
    else:
        # 显示密码修改页面
        return render(request, 'pwdchange.html', {'userInfo': userInfo})
# 首页
@csrf_exempt
def index(request):
    uemail = request.session.get('email')
    userInfo = User.objects.get(email=uemail)
    return render(request, 'index.html', {'userInfo': userInfo})


# 数据分析
# 月温度分析（分析主要的省会城市每月温度）


def monthTempChar(request):
    uemail = request.session.get('email')
    userInfo = User.objects.get(email=uemail)
    dateList = getMonthDate()
    dateList = list(dateList)
    print("传进来的月份列表", dateList)
    context = {
        'userInfo': userInfo,
        'dates': dateList
    }
    return render(request, 'monthTempChar.html', context)

def get_month_data(request):
    selected_month = request.GET.get('month')
    # 根据选择的月份从数据库中获取数据
    # 获取平均高温和平均低温
    xData, y1Data, y2Data = getAverageTemp(selected_month)
    # 获取极端高温和极端低温
    xCityData, y1MaxData, y2MinData=getMinMaxTemp(selected_month)
    return JsonResponse({
        'xData': xData,
        'y1Data': y1Data,
        'y2Data': y2Data,
        'xCityData': xCityData,
        'y1MaxData': y1MaxData,
        'y2MinData': y2MinData
    })


# 月空气质量分析
def monthAirCha(request):
    uemail = request.session.get('email')
    userInfo = User.objects.get(email=uemail)
    dateList = getMonthDate()
    dateList = list(dateList)
    print("传进来的月份列表", dateList)
    context = {
        'userInfo': userInfo,
        'dates': dateList
    }
    return render(request, 'monthAirChar.html', context)
def get_month_air(request):
    selected_month = request.GET.get('month')
    xData, y1Data, y2Data =getMinMaxAir(selected_month)
    xCityData ,yAirData =get_avg_air(selected_month)
    return JsonResponse({
        'xData': xData,
        'y1Data': y1Data,
        'y2Data': y2Data,
        'xCityData': xCityData,
        'yAirData': yAirData
    })


''' 城市数据分析'''
def CityData(request):
    uemail = request.session.get('email')
    userInfo = User.objects.get(email=uemail)
    # 获取所有唯一年份，并过滤掉 weather_date 为 NULL 的记录
    unique_years = WeatherInfo.objects.filter(date__isnull=False).dates('date', 'year', order='DESC')
    cityList=get_city_List()
    cityList = list(cityList)
    if not unique_years:
        unique_years = []  # 如果没有数据，设置为空列表
    else:
        unique_years = [y.strftime("%Y") for y in unique_years]
    context={
        'userInfo': userInfo,
        'cityList': cityList,
        'unique_years': unique_years,
    }
    return render(request, 'cityChar.html',context)


# 年度分析
# 获取城市对应的数据
def get_city_data(request):
    selected_city = request.GET.get('city')
    selected_Year=request.GET.get('date')
    xData, y1Data, y2Data =get_city_temperature(selected_city,selected_Year)
    wetaherList, windList, levelList = get_city_weather(selected_city,selected_Year)
    xCityData,y1CityData,y2CityData =getCityAir(selected_city,selected_Year)
    print("空气质量趋势",xCityData,y1CityData,y2CityData)
    print("天气状况：", wetaherList)
    return JsonResponse({
        'xData': xData,
        'y1Data': y1Data,
        'y2Data': y2Data,
        'wetaherList': wetaherList,
        'windList': windList,
        'levelList': levelList,
        'xCityData': xCityData,
        'y1CityData': y1CityData,
        'y2CityData': y2CityData
    })



# 月份分析

def CityMonth(request):
    uemail = request.session.get('email')
    userInfo = User.objects.get(email=uemail)

    # 获取所有唯一年份，并过滤掉 weather_date 为 NULL 的记录
    unique_years = WeatherInfo.objects.filter(date__isnull=False).dates('date', 'year', order='DESC')
    # 设置默认值
    default_city = "重庆"
    default_year = "2024"
    default_month = "12"
    # 检查 unique_years 是否为空或为 None
    if not unique_years:
        unique_years = []  # 如果没有数据，设置为空列表
    else:
        unique_years = [y.strftime("%Y") for y in unique_years]

    print('unique_years', unique_years)
    context = {
        'userInfo': userInfo,
        'cityList': list(get_city_List()),
        'unique_years': unique_years,
        'default_city': default_city,
        'default_year': default_year,
        'default_month': default_month
    }
    return render(request, 'cityMonthChar.html', context)

def get_city_month_data(request):
    selected_city = request.GET.get('city')
    selected_year = request.GET.get('year')
    selected_month = request.GET.get('month')

    # 组合成YYYY-MM格式
    date_str = f"{selected_year}-{selected_month.zfill(2)}"

    # 原有数据处理逻辑保持不变
    xdata, y1data, y2data, y3data = getMonthWeather(selected_city, date_str)
    # ...其他数据获取...
    avg_high_temperature, avg_low_temperature, high_temperature, low_temperature, high_air, low_air = getMonthCard(
        selected_city, date_str)
    x1data, y1winddata = getMonthWind(selected_city, date_str)

    return JsonResponse({
        'xData': xdata,
        'y1Data': y1data,
        'y2Data': y2data,
        'y3Data': y3data,
        'avg_high_temperature': avg_high_temperature,
        'avg_low_temperature': avg_low_temperature,
        'high_temperature': high_temperature,
        'low_temperature': low_temperature,
        'high_air': high_air,
        'low_air': low_air,
        'x1Data': x1data,
        'y1windData': y1winddata
    })



def get_available_months(request):
    selected_year = request.GET.get('year')
    # 从数据库获取该年份下所有存在的月份
    months = WeatherInfo.objects.filter(
        date__startswith=selected_year
    ).dates('date', 'month', order='ASC')
    # 格式化为两位数字符串
    month_list = [m.strftime("%m") for m in months]
    return JsonResponse({'months': month_list})




# 天气大屏
def screen(request):
    cityList=get_city_List()
    cityList=list(cityList)
    # 设置默认城市为重庆
    default_city = '重庆'

    # 设置默认日期为 WeatherInfo 中日期的最后一天
    default_date = WeatherInfo.objects.last().date.strftime('%Y-%m-%d') if WeatherInfo.objects.exists() else None
    context={
        'cityList':cityList,
        'default_date': default_date,
        'default_city': default_city
        }
    return render(request,'dashboard.html',context)

@csrf_exempt
def screendata(request):
    selected_date = request.POST.get('selectedDate',None)
    selected_city = request.POST.get('selectedCity','重庆')  # 获取选择的城市

    if not selected_date:
        # 如果没有选择日期，则使用默认日期
        selected_date = WeatherInfo.objects.last().date.strftime('%Y-%m-%d') if WeatherInfo.objects.exists() else None
    weather_data = getweatherInfo(selected_date)
    max_temp_data = get_max_temp_data(selected_date)
    print(max_temp_data)
    city_count=get_city_count(selected_date)

    # 统计最高温城市和最低温城市
    max_temp_city = max(max_temp_data, key=lambda x: x['maxtemp']) if max_temp_data else {}
    min_temp_city = min(max_temp_data, key=lambda x: x['mintemp']) if max_temp_data else {}
    print("右上：",city_count, max_temp_city, min_temp_city)
    # 获取天气状况与温度关系数据
    weather_temp_relation = get_weather_max_temp(selected_date)
    print("散点图数据：",weather_temp_relation)
    # 天气情况占比
    weather_distribution=get_weather_distribution(selected_date)
    print("天气情况占比",weather_distribution)
    # 风向占比
    wind_distribution=get_wind_distribution(selected_date)
    print("风向占比",wind_distribution)
    map_data=getmapdata(selected_date)
    print("地图数据",map_data)

    # 获取过去30天的温度数据
    past_30_days_dates, past_30_days_temps ,past_30_days_mintemps= get_past_30_days_temp(selected_city, selected_date)
    print('折线图数据：',past_30_days_dates,past_30_days_temps,past_30_days_mintemps)

    return JsonResponse({
        'weather_data': weather_data,
        'max_temp_data': max_temp_data,
        'city_count': city_count,
        'max_temp_city': max_temp_city.get('city', '') if max_temp_city else '',
        'min_temp_city': min_temp_city.get('city', '') if min_temp_city else '',
        'weather_temp_relation': weather_temp_relation,
        'weather_distribution': weather_distribution,
        'wind_distribution': wind_distribution,
        'map_data': map_data,
        'past_30_days_dates': past_30_days_dates,
        'past_30_days_temps': past_30_days_temps,
        'past_30_days_mintemps': past_30_days_mintemps

    }, safe=False)



# 详情信息
def weather_deatil_view(request):
    uemail = request.session.get('email')
    userInfo = User.objects.get(email=uemail)
    cityList = get_city_List()
    print(cityList)
    city = request.GET.get('city') or '重庆'
    tableData = list(getTableData(city))
    print(tableData)
    context={
        'userInfo': userInfo,
        'cityList': cityList,
        'defaultCity': city,
        'tableData': tableData
    }
    return render(request, 'tableData.html',context)



'''智能问答'''
def chatAI(request):
    return render(request,'chat.html')
# 初始化 OpenAI 客户端
client = OpenAI(
    api_key="sk-9gg7R30vFqLxFzjHI7O8oSltooiuFMypAOlejjHJRCLAlDxb",
    base_url="https://api.moonshot.cn/v1"
)

@csrf_exempt
@require_POST
def chat(request):
    # 获取前端传递的消息
    user_message = request.POST.get('message', '')
    # 如果消息为空，返回默认欢迎消息
    if not user_message:
        return JsonResponse({"status": "success", "response": "你好我是智能问答助手小k,很高兴见到你"})

    try:
        completion = client.chat.completions.create(
            model="moonshot-v1-8k",
            messages=[
                {"role": "system", "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。"},
                {"role": "user", "content": user_message}
            ],
            temperature=0.3,
        )
        response = completion.choices[0].message.content
        return JsonResponse({"status": "success", "response": response})
    except Exception as e:
        return JsonResponse({"status": "error", "message": str(e)})


'''天气预报'''
def weatherforecast(request):
    uemail = request.session.get('email')
    userInfo = User.objects.get(email=uemail)
    cityList = get_city_List()

    context={
        'userInfo': userInfo,
        'cityList': cityList
    }
    return render(request, 'forecast.html', context)
def weather_prediction(request):
    if request.method == 'POST':
        city = request.POST.get('city')

        try:
            # 生成城市CSV
            generate_city_csv(city)

            # 执行预测
            predictions = predict_weather()

            # 格式化日期并提取预测数据
            formatted_predictions = []
            dates = []
            temp1_values = []
            temp2_values = []
            for item in predictions:
                date_str = item['Date'].strftime('%Y-%m-%d')
                # 保留两位小数
                temp1 = round(item['Predicted_Temp1'], 2)
                temp2 = round(item['Predicted_Temp2'], 2)
                formatted_predictions.append({
                    'Date': date_str,
                    'Predicted_Temp1': temp1,
                    'Predicted_Temp2': temp2
                })
                dates.append(date_str)
                temp1_values.append(temp1)
                temp2_values.append(temp2)

            # 准备返回的数据
            chart_data = {
                'dates': dates,
                'temp1': temp1_values,
                'temp2': temp2_values
            }
            print("预测数据",city,chart_data)

            return JsonResponse({'status': 'success', 'data': formatted_predictions, 'chart_data': chart_data})

        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)})



@csrf_exempt
def predict(request):
    uemail = request.session.get('email')
    userInfo = User.objects.get(email=uemail)
    windList = getWindList()
    dateList = geteveryDate()
    print("")
    cites = get_city_List()
    city = request.GET.get('city') or cites[0]
    if request.method == 'POST':
        defaultDate = request.POST.get('date') or dateList[0]

        defaultWind = request.POST.get('wind') or dateList[0]

        city = request.POST.get('city') or cites[0]
        # 查询天气状况
        weather_info = WeatherInfo.objects.filter(date=defaultDate, city__startswith=city).first()
        if weather_info:
            weatherInfo = weather_info.wearther
        else:
            weatherInfo = "未找到天气信息"
        print("实际天气情况",weatherInfo)
        print(defaultDate, defaultWind, city)
        print(defaultDate)
        result = preModel(1, [defaultDate, defaultWind, city])
        print(result)
        return render(request, 'predict.html', {
            'userInfo': userInfo,
            'dateList': dateList,
            'defaultDate': defaultDate,

            'windList': windList,
            'defaultWind': defaultWind,

            'cites': cites,
            'defaultCity': city,
            'result': result,
            'weatherInfo': weatherInfo
        })
    return render(request, 'predict.html', {
        'userInfo': userInfo,
        'windList': windList,
        'dateList': dateList,
        'cites': cites
    })


# 历史天气详情
# 获取历史天气信息
@csrf_exempt
def list_all_weatherInfo(request):
    if request.method == 'GET':
        try:
            # 查询所有历史天气信息
            # 获取请求参数中的城市，如果没有则默认使用重庆
            city = request.GET.get('city', '重庆')
            # 查询指定城市的所有历史天气信息
            weatherInfos = WeatherInfo.objects.filter(city=city)
            weatherInfo_list = []
            for weather in weatherInfos:
                weatherInfo_info = {
                    'id': weather.id,
                    'city': weather.city,
                    'date': weather.date,
                    'weekDay': weather.weekDay,
                    'mastHeightDay': weather.mastHeightDay,
                    'mastSmallDay': weather.mastSmallDay,
                    'wearther': weather.wearther,
                    'wind': weather.wind,
                    'windlevel': weather.windlevel,
                    'mastHight': weather.mastHeight,
                    'mastSmall': weather.mastSmall,
                }
                weatherInfo_list.append(weatherInfo_info)

            return JsonResponse({'data': weatherInfo_list}, status=200)
        except Exception as e:
            return JsonResponse({'message': str(e)}, status=500)
    else:
        return JsonResponse({'message': '无效的请求方法'}, status=405)



@csrf_exempt
def get_weather_data(request):
    if request.method == 'POST':
        # 获取前端传来的城市名和年月
        data = json.loads(request.body)
        city_name = data.get('city')
        year_month = data.get('year_month')
        if not city_name or not year_month:
            return JsonResponse({'error': '缺少必要参数'}, status=400)
        # 根据城市名和年月过滤数据
        weather_data = WeatherInfo.objects.filter(city=city_name, date__startswith=year_month)
        # 提取最高温度、最低温度和风向风级数据
        highest_temps = [weather.mastHeightDay for weather in weather_data if weather.mastHeightDay is not None]
        lowest_temps = [weather.mastSmallDay for weather in weather_data if weather.mastSmallDay is not None]


        # 统计每个风力等级的数量
        # 统计每个风力等级的数量
        wind_levels = [
            w.windlevel.strip()  # 假设字段名为windlevel，去除前后空格
            for w in weather_data
            if w.windlevel and w.windlevel.strip() != ''
        ]
        # 使用Counter统计风力等级频次
        wind_level_counts = dict(Counter(wind_levels))

        # 统计风向数据
        wind_directions = [
            w.wind.strip()  # 假设字段名为windDirection，去除前后空格
            for w in weather_data
            if w.wind and w.wind.strip() != ''
        ]

        # 使用Counter统计风向频次
        wind_directions = dict(Counter(wind_directions))


        print('wind_level_counts',wind_level_counts)
        # 构造返回数据
        response_data = {
            'highest_temps': highest_temps,
            'lowest_temps': lowest_temps,
            'wind_level_counts': wind_level_counts
        }
        print(response_data)
        return JsonResponse(response_data)
    return JsonResponse({'error': '不支持的请求方法'}, status=405)